import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_cors import CORS

# 初始化扩展
db = SQLAlchemy()

def create_app(test_config=None):
    # 创建并配置应用
    app = Flask(__name__, instance_relative_config=True)
    
    # 默认配置
    app.config.from_mapping(
        SECRET_KEY=os.environ.get('SECRET_KEY', 'dev_secret_key'),
        SQLALCHEMY_DATABASE_URI=os.environ.get('DATABASE_URL', 'sqlite:///instance/dev.db'),
        SQLALCHEMY_TRACK_MODIFICATIONS=False,
    )

    # 根据环境加载配置
    if test_config is None:
        # 非测试模式，加载实例配置
        app.config.from_pyfile('config.py', silent=True)
    else:
        # 测试模式，加载测试配置
        app.config.from_mapping(test_config)

    # 确保实例文件夹存在
    try:
        os.makedirs(app.instance_path)
    except OSError:
        pass

    # 初始化扩展
    db.init_app(app)
    
    # 配置CORS
    CORS(app)
    
    # 注册蓝图
    from .api import api_bp
    app.register_blueprint(api_bp, url_prefix='/api')
    
    # 简单的首页路由
    @app.route('/')
    def index():
        return {
            "app": "MVP Backend",
            "version": "1.0.0",
            "status": "running"
        }

    return app